<?php
/**
 * Created by PhpStorm.
 * User: 程阳
 * Date: 2018/4/1
 * Time: 19:21
 */

namespace app\api\service;

use app\api\model\Order;
use app\api\model\Product;
use app\api\service\Order as OrderService;
use app\lib\enum\OrderStatusEnum;
use think\Db;
use think\Exception;
use think\Log;

class WxNotify
{
    /**
     * 模拟微信支付回调接口
     * @param $data
     * @param $msg
     * @return bool
     */
    public function NotifyProcess($data,&$msg){
        $orderNo = $data['order_no'];
        Db::startTrans();
        try{
            $order = Order::where('order_no','=',$orderNo)->lock(true)->find();
            if($order->status == 1){
                $service = new OrderService();
                $status = $service->checkOrderStock($order->id);
                if($status['pass']){ // 库存充足
                    $this->updateOrderStatus($order->id,true);
                    $this->reduceStock($status);
                }else{ // 库存不足
                    $this->updateOrderStatus($order->id,false);
                }
            }
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            Log::error($e);
            // 如果出现异常，向微信返回false，请求重新发送通知
            return false;
        }
        
        return true;
    }
    
    /**
     * 更新订单中所有商品的库存
     * @param $status
     */
    private function reduceStock($status){
        foreach ($status['pStatusArray'] as $singlePStatus){
            Product::where('id','=',$singlePStatus['id'])->setDec('stock',$singlePStatus['count']);
        }
    }
    
    /**
     * 根据库存状态更新订单状态
     * @param $orderID
     * @param $success
     */
    private function updateOrderStatus($orderID,$success){
        $status = $success ? OrderStatusEnum::PAID : OrderStatusEnum::PAID_BUT_OUT_OF;
        Order::where('id','=',$orderID)->update(['status' => $status]);
    }
}